package cn.fzc.yipai.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.rmi.ServerException;

/**
 * @Author: fu.zc
 * @Date: 2021/6/15 10:07
 * @Description:
 */
@Slf4j
@Component
public class HttpUtils {

    private final RestTemplate restTemplate;

    @Autowired
    public HttpUtils(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }


    private HttpHeaders getHeader(String token) {
        //加入请求头
        HttpHeaders headers = new HttpHeaders();
        headers.add("ACCESSTOKEN", token);
        headers.add("Origin", "https://www.yihui-xh.xyz");
        headers.add("Host", "www.yihui-xh.xyz");
        headers.add("Referer", "https://www.yihui-xh.xyz/h5/");
        headers.add("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1");
        return headers;
    }


    public <T> String executePost(String url, String token, T param) throws ServerException {
        HttpEntity<Object> entity = new HttpEntity<>(param, getHeader(token));
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, entity, String.class);

        if (responseEntity.getStatusCode() != HttpStatus.OK) {
            throw new IllegalStateException("Http POST 请求失败");
        }
        return responseEntity.getBody();
    }

    public String executeGet(String url, String token) {
        HttpEntity<Object> entity = new HttpEntity<>(null, getHeader(token));
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);

        if (responseEntity.getStatusCode() != HttpStatus.OK) {
            throw new IllegalStateException("Http GET 请求失败");
        }
        return responseEntity.getBody();
    }

}
